from collections import defaultdict
from datetime import datetime

from flask import Blueprint, request
from sqlalchemy import null, or_, and_, func
from sqlalchemy.exc import SQLAlchemyError
from response import success_response,error_response

from extension import db
from models import Book, NewBorrow

bookForm_bp = Blueprint('bookForm', __name__)

@bookForm_bp.route('/api/bookForm/totalNumber',methods=['GET',])
def totalNumber():
    book_counts = db.session.query(Book.category, func.count(Book.bookId).label('count')).group_by(Book.category).all()
    result = [
        {
            "categoryName": book.category,
            "totalNumber": book.count
        }for book in book_counts
    ]
    return {
        "code": "SUCCESS",
        "message": "SUCCESS",
        "data": {
            "formMsg": result
        }
    }

@bookForm_bp.route('/api/bookForm/newBorrowNumber',methods=['GET',])
def newBorrowNumber():
    newBorrows=NewBorrow.query.all()
    result = [
        {
            "newBorrowId": newBorrow.newBorrowId,
            "month": newBorrow.month,
            "categoryName": newBorrow.categoryName,
            "quantity": newBorrow.quantity
        }for newBorrow in newBorrows
    ]
    return {
        "code": "SUCCESS",
        "message": "SUCCESS",
        "data": {
            "newBorrows": result
        }
    }
